package com.amor.widget

import android.app.Activity
import android.content.Context
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.amor.demo.web1.R
import com.amor.util.StatusBarUtil
import com.hy.frame.util.AutoUtil

class ToolbarUI(context: Context, leftCallback: Runnable? = null, rightCallback: Runnable? = null) : com.hy.frame.ui.ToolbarUI(context, leftCallback, rightCallback) {

    override fun getLayoutId(): Int {
        if (mLeftIcon != null)
            return R.layout.in_header_back
        return super.getLayoutId()
    }

    private fun getToolbarHeight(): Int {
        val attr = intArrayOf(R.attr.appToolbarHeight)
        val array = context.theme.obtainStyledAttributes(attr)
        val headerHeight = array.getDimensionPixelSize(0, resources.getDimensionPixelSize(R.dimen.header_height))
        array.recycle()
        return headerHeight
    }

    override fun build(act: AppCompatActivity?, container: ViewGroup?, params: ViewGroup.LayoutParams?): com.hy.frame.ui.ToolbarUI {
        //设置头高度 为缩放高度
        if (HEARER_HEIGHT == 0) {
            HEARER_HEIGHT = AutoUtil.calDesignSizeWithPX(context, getToolbarHeight())
        }
        setToolbarHeight(HEARER_HEIGHT)
        if (STATUS_BAR_HEIGHT == 0) {
            if (context is Activity) {
                (context as Activity).window.decorView.post {
                    STATUS_BAR_HEIGHT = StatusBarUtil.getStatusBarHeight(context as Activity)
                    setStatusBarHeight(STATUS_BAR_HEIGHT)
                    super.build(act, container, params)
                    resetHeaderHeight()
                }
                return this
            }
        }
        setStatusBarHeight(STATUS_BAR_HEIGHT)
        super.build(act, container, params)
        resetHeaderHeight()
        return this
    }

    private fun resetHeaderHeight() {
        if (isTranslucentStatus) return
        if (mToolbarHeight > 0 && mToolbar != null) {
            var lp = mToolbar.layoutParams
            if (lp == null) {
                lp = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, mToolbarHeight)
            } else {
                lp.height = mToolbarHeight
            }
            mToolbar.layoutParams = lp
        }
    }

    /**
     * 自动配置返回返回
     */
    fun back(): ToolbarUI {
        this.setLeftIcon(R.mipmap.ic_back)
        this.mLeftCallback = Runnable {
            if (context is Activity) {
                (context as Activity).onBackPressed()
            }
        }
        return this
    }

    companion object {
        var HEARER_HEIGHT: Int = 0
        var STATUS_BAR_HEIGHT: Int = 0
    }
}